package network;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Mariam
 */
public class ThreadSendFile extends Thread {

    private Socket socket;
    private File file;

    /**
     * Constructs a thread that will send a message in UDP
     * @param socket the socket used to send the message
     * @param addr ths IP address of the remote user (receiver of the message)
     * @param file the file to send
     * @param parent the chatNI which has created the thread
     */
    public ThreadSendFile(Socket socket, InetAddress addr, File file, ChatNI parent) {
        try {
            this.socket = new Socket(addr, parent.COMMON_PORT_SEND_TCP);
            this.file = file;
        } catch (IOException ex) {
            Logger.getLogger(ThreadSendFile.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void run() {
        //System.out.println("Sending of a file");
        InputStream inputFile = null;
        OutputStream outputFile = null;

        try {
            inputFile = new FileInputStream(file);
            outputFile = this.socket.getOutputStream();
            byte[] bufSending = new byte[1024];

            int i;
            while ((i = inputFile.read(bufSending, 0, 1024)) != -1) {
                outputFile.write(bufSending, 0, i);
            }
            //System.out.println("envoi fichier fini !!");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ThreadSendFile.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ThreadSendFile.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                inputFile.close();
                outputFile.flush();
                outputFile.close();
            } catch (IOException ex) {
                Logger.getLogger(ThreadSendFile.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }
}